#include "inc/zg291.h"
#include "ui_zg291.h"
#include "stdint.h"
#include <QTimer>   // 必须包含
#include <QDebug>   // 调试用
#include <QMessageBox>
#include <QTime>
#include <QThread>
ZG291::ZG291(QSerialPort *serialPort,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ZG291),
    serialPort(serialPort)
{
    ui->setupUi(this);
//    read_rtdata = new QTimer(this);
//    connect(read_rtdata, &QTimer::timeout, this, &ZG291::read_devicezg291rtdata);
    connect(ui->treeWidget, &QTreeWidget::itemClicked, this,&ZG291::on_treeWidget_itemClicked);
//    read_rtdata->start(2000);
//    read_serson_en();
}

ZG291::~ZG291()
{
    delete ui;
}

void ZG291::on_treeWidget_itemClicked(QTreeWidgetItem *item, int column)
{
    Q_UNUSED(column);
    QWidget *currentWidget = ui->stackedWidget->currentWidget();
        if (currentWidget) {
            ui->stackedWidget->removeWidget(currentWidget);
            currentWidget->deleteLater();
        }
        int index = item->parent()->indexOfChild(item);
        switch(index) {
                case 0:  // GLOBAL - 总是可用
                    break;
                case 1:  // 温度
                    if(!TEMP_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持温度传感器");
                        return;
                    }
                    break;
                case 2:  // 湿度
                    if(!HUM_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持湿度传感器");
                        return;
                    }
                    break;
                case 3:  // PM1.0
                    if(!PM1_0_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持PM1.0传感器");
                        return;
                    }
                    break;
                case 4:  // PM2.5
                    if(!PM2_5_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持PM2.5传感器");
                        return;
                    }
                    break;
                case 5:  // PM10
                    if(!PM10_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持PM10传感器");
                        return;
                    }
                    break;
                case 6:  // TVOC
                    if(!TVOC_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持TVOC传感器");
                        return;
                    }
                    break;
                case 7:  // 大气压
                    if(!BORD_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持大气压传感器");
                        return;
                    }
                    break;
                case 8:  // 甲醛
                    if(!CH2O_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持甲醛传感器");
                        return;
                    }
                    break;
                case 9:  // 二氧化碳
                    if(!CO2_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持二氧化碳传感器");
                        return;
                    }
                    break;
                case 10: // 异味
                    if(!PECU_enabled) {
                        QMessageBox::warning(this, "不支持", "当前设备不支持异味传感器");
                        return;
                    }
                    break;
                default:
                    return;
            }
        switch(index)
        {
            case 0:
            zg291global=new ZG291GLOBAL(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291global);
            ui->stackedWidget->setCurrentWidget(zg291global);
            break;
        case 1:
            zg291temp_para=new ZG291temper_para(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291temp_para);
            ui->stackedWidget->setCurrentWidget(zg291temp_para);
            break;
        case 2:
            zg291_hum_para=new ZG291hum_para(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291_hum_para);
            ui->stackedWidget->setCurrentWidget(zg291_hum_para);
            break;
        case 3:
            zg291pm1_0_para=new ZG291_PM1_0(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291pm1_0_para);
            ui->stackedWidget->setCurrentWidget(zg291pm1_0_para);
            break;
        case 4:
            zg291pm2_5_para=new ZG291PM2_5_para(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291pm2_5_para);
            ui->stackedWidget->setCurrentWidget(zg291pm2_5_para);
            break;
        case 5:
            zg291pm10_para=new ZG291PM10_para(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291pm10_para);
            ui->stackedWidget->setCurrentWidget(zg291pm10_para);
            break;
        case 6:
            zg291tvoc_para=new ZG291TVOC_PARA(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291tvoc_para);
            ui->stackedWidget->setCurrentWidget(zg291tvoc_para);
            break;
        case 7:
            zg291bora_para=new ZG291BORA_para(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291bora_para);
            ui->stackedWidget->setCurrentWidget(zg291bora_para);
            break;
        case 8:
            zg291ch20_para=new ZG291CH2O_PARA(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291ch20_para);
            ui->stackedWidget->setCurrentWidget(zg291ch20_para);
            break;
        case 9:
            zg291co2_para=new ZG291CO2_PARA(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291co2_para);
            ui->stackedWidget->setCurrentWidget(zg291co2_para);
            break;
        case 10:
            zg291_pecu_para=new zg291pecu_para(serialPort,read_rtdata);
            ui->stackedWidget->addWidget(zg291_pecu_para);
            ui->stackedWidget->setCurrentWidget(zg291_pecu_para);
            break;
        default:
            break;
        }
}
void ZG291::read_serson_en()
{
    // 从机地址和功能码
    const quint8 slaveAddress = 0x00;
    const quint8 functionCode = 0x03; // 读取保持寄存器

    // 要读取的寄存器列表（每个寄存器2字节）
    QVector<quint16> registers = {
        0x1a, 0x25, 0x30, 0x3b, 0x46, 0x51, 0x5c, 0x67, 0x72, 0x7d
    };

    // 遍历所有寄存器，逐个发送请求
    for (int i = 0; i < registers.size(); ++i) {
        QByteArray request;
        // 构造Modbus请求帧
        request.append(slaveAddress);                     // 从机地址
        request.append(functionCode);                     // 功能码
        request.append(static_cast<char>(0x00)); // 寄存器地址高字节
        request.append(static_cast<char>(registers[i] & 0xFF));        // 寄存器地址低字节
        request.append(static_cast<char>(0x00));                             // 读取数量高字节（固定1）
        request.append(0x01);                             // 读取数量低字节（固定1）

        // 计算CRC并添加到请求帧末尾
        quint16 crc = calculateCRC(request);
        request.append(static_cast<char>(crc & 0xFF));    // CRC低字节
        request.append(static_cast<char>((crc >> 8) & 0xFF)); // CRC高字节

        // 通过串口发送请求
        serialPort->write(request);
        if (!serialPort->waitForBytesWritten(1000)) {
            qDebug() << "[" << QTime::currentTime().toString("hh:mm:ss.zzz") << "]"
                     << "发送请求超时，寄存器地址:" << QString::number(registers[i], 16);
            continue;
        }

        // 添加250ms延时（使用QThread::msleep需要包含<QThread>）
        QThread::msleep(300);

        // 等待并读取响应
        if (serialPort->waitForReadyRead(1000)) {
            QByteArray response = serialPort->readAll();
            while (serialPort->waitForReadyRead(50)) {  // 改为50ms更合理
                response += serialPort->readAll();
            }

            // 校验响应有效性（最小长度5字节）
            if (response.size() >= 5) {
                // 提取接收到的CRC
                quint16 receivedCrc = static_cast<quint8>(response.at(response.size() - 2)) |
                                    (static_cast<quint8>(response.at(response.size() - 1)) << 8);
                // 计算响应数据的CRC
                quint16 responseCrc = calculateCRC(response.left(response.size() - 2));

                if (responseCrc == receivedCrc) {
                    // 解析寄存器值（大端序）
                    quint16 value = static_cast<quint8>(response.at(3))<<8 |
                                    (static_cast<quint8>(response.at(4)));

                    // 根据寄存器顺序更新全局变量
                    switch (i) {
                        case 0: TEMP_enabled = (value != 0); break;
                        case 1: HUM_enabled = (value != 0); break;
                        case 2: PM1_0_enabled = (value != 0); break;
                        case 3: PM2_5_enabled = (value != 0); break;
                        case 4: PM10_enabled = (value != 0); break;
                        case 5: TVOC_enabled = (value != 0); break;
                        case 6: BORD_enabled = (value != 0); break;
                        case 7: CH2O_enabled = (value != 0); break;
                        case 8: CO2_enabled = (value != 0); break;
                        case 9: PECU_enabled = (value != 0); break;
                    }
                    qDebug() << "[" << QTime::currentTime().toString("hh:mm:ss.zzz") << "]"
                             << QString("寄存器 0x%1 读取成功，值: %2")
                                .arg(registers[i], 0, 16)
                                .arg(value);
                } else {
                    qDebug() << "[" << QTime::currentTime().toString("hh:mm:ss.zzz") << "]"
                             << "CRC校验失败，寄存器地址:" << QString::number(registers[i], 16)
                             << "接收CRC:" << receivedCrc
                             << "计算CRC:" << responseCrc;
                }
            } else {
                qDebug() << "[" << QTime::currentTime().toString("hh:mm:ss.zzz") << "]"
                         << "响应长度无效，寄存器地址:" << QString::number(registers[i], 16)
                         << "实际长度:" << response.size();
            }
        } else {
            qDebug() << "[" << QTime::currentTime().toString("hh:mm:ss.zzz") << "]"
                     << "等待响应超时，寄存器地址:" << QString::number(registers[i], 16);
        }
    }
}
//void ZG291::read_devicezg291rtdata()
//{
//    if (!serialPort || !serialPort->isOpen()) {
//        qDebug() << "Serial port not ready!";
//        return;
//    }

//    // Modbus RTU 请求帧
//    QByteArray request;
//    request.append(static_cast<char>(0x00));    // 从机地址 00
//    request.append(static_cast<char>(0x04));    // 功能码 04
//    request.append(static_cast<char>(0x00));    // 起始地址高字节 00
//    request.append(static_cast<char>(0x00));    // 起始地址低字节 00
//    request.append(static_cast<char>(0x00));    // 寄存器数高字节 00
//    request.append(static_cast<char>(0x0A));    // 寄存器数低字节 0A (10个寄存器)

//    // 计算CRC16
//    quint16 crc = calculateCRC(request);
//    request.append(static_cast<char>(crc & 0xFF));      // CRC低字节
//    request.append(static_cast<char>((crc >> 8) & 0xFF)); // CRC高字节

//    // 发送请求
//    if (serialPort->write(request) == -1) {
//        qDebug() << "Received data:" << request.toHex();
//        qDebug() << "Write failed:" << serialPort->errorString();
//    } else {
//        if (serialPort->waitForReadyRead(1000)) {
//            QByteArray response = serialPort->readAll();
//            while (serialPort->waitForReadyRead(10)) {
//                response += serialPort->readAll();
//            }

//            // 解析响应并更新UI
//            qDebug() << "Received data:" << response.toHex();
//            if(response.size() >= 25) {  // 最小响应长度检查
//                // 温度 (寄存器0)
//                quint16 temp = (static_cast<quint8>(response[3]) << 8) | static_cast<quint8>(response[4]);
//                ui->RTtemper->setText(QString::number(temp/10.0, 'f', 1));

//                // 湿度 (寄存器1)
//                quint16 hum = (static_cast<quint8>(response[5]) << 8) | static_cast<quint8>(response[6]);
//                ui->RThum->setText(QString::number(hum/10.0, 'f', 1));

//                // PM1.0 (寄存器2)
//                quint16 pm1_0 = (static_cast<quint8>(response[7]) << 8) | static_cast<quint8>(response[8]);
//                ui->RTpm1_0->setText(QString::number(pm1_0));

//                // PM2.5 (寄存器3)
//                quint16 pm2_5 = (static_cast<quint8>(response[9]) << 8) | static_cast<quint8>(response[10]);
//                ui->RTpm2_5->setText(QString::number(pm2_5));

//                // PM10 (寄存器4)
//                quint16 pm10 = (static_cast<quint8>(response[11]) << 8) | static_cast<quint8>(response[12]);
//                ui->RTPM10->setText(QString::number(pm10));

//                // TVOC (寄存器5)
//                quint16 tvoc = (static_cast<quint8>(response[13]) << 8) | static_cast<quint8>(response[14]);
//                ui->RTTVOC->setText(QString::number(tvoc));

//                // 大气压 (寄存器6)
//                quint16 pressure = (static_cast<quint8>(response[15]) << 8) | static_cast<quint8>(response[16]);
//                ui->RTBORD->setText(QString::number(pressure/100.0,'f',2));

//                // 甲醛 (寄存器7)
//                quint16 ch2o = (static_cast<quint8>(response[17]) << 8) | static_cast<quint8>(response[18]);
//                ui->RTCH2O->setText(QString::number(ch2o));

//                // 二氧化碳 (寄存器8)
//                quint16 co2 = (static_cast<quint8>(response[19]) << 8) | static_cast<quint8>(response[20]);
//                ui->R4TCO2->setText(QString::number(co2));

//                // 异味 (寄存器9)
//                quint16 pecu = (static_cast<quint8>(response[21]) << 8) | static_cast<quint8>(response[22]);
//                ui->RTPECU->setText(QString::number(pecu/1000.0,'f',3));
//            } else {
//                qDebug() << "Invalid response length:" << response.size();
//            }
//        } else {
//            qDebug() << "Read timeout!";
//        }
//    }
//}
